import time
import requests
from pyquery import PyQuery as jq
import os
from PIL import Image
from io import BytesIO
import img2pdf
import shutil
from loguru import logger as log
import uuid

from util.console import *
from util.common import *

def mkdir(path):
    if not os.path.exists(path):
        os.mkdir(path)

TMP_DIR_NAME = 'tmp'
BUILD_PATH = "build"

log.add('spring.log')
log.info('test')
log.debug('test')
log.warning('test')
log.error('test')
log.success('test')

mkdir(TMP_DIR_NAME)
mkdir(BUILD_PATH)

img_index = 0

def get_filename_from_url(src):
    return src[src.rindex('/')+1:]+".png"

def random_filename(index,filename):
    return str(uuid.uuid5(uuid.NAMESPACE_DNS, str(index)+'/'+filename))+".png"

def save_origin_img(filename,img_content):
    Image.open(BytesIO(img_content)).save(filename)

# def convert_webp_to_png(src,dest):
#     Image.open(src).save(dest)

# def get_content_from_url(url):
#     return requests.get(url).content

def get_request(url):
    return requests.get(url,stream=True)

# def save_origin_file(filename,r):
#     with open(filename, 'wb') as fd:
#         for chunk in r.iter_content(chunk_size=128):
#             fd.write(chunk)


def get_whole_content(r):
    data = bytes()
    for chunk in r.iter_content(chunk_size=128):
        data += chunk
    return data



# t1 = time.perf_counter()
# q = jq(url='https://www.baidu.com/',encoding='utf-8')
# p(time.perf_counter() - t1)
#
# imgurl = "https:"+q('img').attr('src');
# p(imgurl)
# img = requests.get(imgurl)
# with open('test.png','wb') as f:
#     f.write(img.content)
#
# i = Image.open(BytesIO(img.content))
# i.save('test2.png')


# =========== download ==================

headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
              'Accept-Encoding': 'gzip, deflate, br',
   
           }


def html(url,encoding='utf-8'):
    # infer params name !!! otherwise error
    hc = requests.get(url,headers=headers).content.decode('utf-8');
    log.info(hc)
    return jq(hc)
    # return jq(url=url,encoding=encoding)

remote_host = ''
remote_home_page = ''

def download_image(img_path, src):
    time.sleep(3)
    r = get_request(src)
    content = get_whole_content(r)
    save_origin_img(img_path, content)


def download_chapter(chapter_url):
    global img_index
    log.info("chapter "+str(img_index)+" download ..."+chapter_url)
    img_name_list = []
    q = html(remote_host+chapter_url)
    img_q = q('div div img')
    log.info(img_q)
    for img in img_q.items():
        log.info(img)
        # src = img.attr('src')
        src = img.attr('data-original')

        # filename = get_filename_from_url(src)
        filename = random_filename(img_index,src)
        log.info('^>>>>>$:'+filename)
        img_path = TMP_DIR_NAME+'/'+filename
        log.info('^<<<<<$:'+img_path)

        retry(3,download_image,img_path,src)
        # download_image(img_path, src)

        img_name_list.append(img_path)


    log.info(img_name_list)

    with open(BUILD_PATH+"/"+str(img_index)+".pdf","wb") as f:
        f.write(img2pdf.convert(img_name_list))

    log.info("chapter "+str(img_index)+" downloaded over")

    img_index += 1

    img_name_list.clear()



q = html(remote_host+remote_home_page)

content_ul = q('ul#detail-list-select')
log.info(content_ul)

# log.info(dir(content_ul))

for link_item_a in content_ul('li>a').items():
    log.info(link_item_a)
    chapter_link = link_item_a.attr('href')
    log.info(chapter_link)
    download_chapter(chapter_link)


log.info("all download over")


# img_name_list = []
# q = html(remote_host+'/details/2932')
# img_q = q('div div img')
# log.info(img_q)
# for img in img_q.items():
#     log.info(img)
#     # src = img.attr('src')
#     src = img.attr('data-original')
#     time.sleep(1)
#     filename = get_filename_from_url(src)
#     log.info('^>>>>>$:'+filename)
#     r = get_request(src)
#     img_path = TMP_DIR_NAME+'/'+filename
#     content = get_whole_content(r)
#     save_origin_img(img_path,content)
#     img_name_list.append(img_path)
#
#
#
# log.info(img_name_list)
#
# with open(BUILD_PATH+"/wuming.pdf","wb") as f:
#     f.write(img2pdf.convert(img_name_list))
#
# img_name_list.clear()




















# shutil.rmtree(TMP_DIR_NAME)